import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/core/utils/user_manager.dart';
import 'package:enterprise_v6_app/app/data/entities/auth/face_recog_entity.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';

abstract final class FaceAuthApi {
  /// 识别
  static Future<bool> recog(String faceImgBase64) async {
    final personId = UserManager.getUserId();
    if (personId == null) {
      AppToast.showError('无人员ID');
      return false;
    }
    SmartDialog.showLoading(backDismiss: true);
    try {
      final resp = await Dio().post<String>(
        Interface.faceRecogUrl,
        data: {
          'imagebase64': faceImgBase64,
          'person_id': personId,
        },
      );
      final data = await compute(
        FaceRecogEntity.fromJson,
        json.decode(resp.data ?? '') as Map<String, dynamic>,
      );
      final item = data.results?.where((e) => e.personId == personId).toList();
      final val = item?.firstOrNull?.simil ?? 0;
      return val > 0.8;
    } finally {
      SmartDialog.dismiss();
    }
  }

  /// 添加 / 更新
  static Future<void> add(String faceImgBase64) async {
    final personId = UserManager.getUserId();
    if (personId == null) {
      AppToast.showError('无人员ID');
      return;
    }
    await HttpUtil().generatePostRequest<String>(
      Interface.faceAddUrl,
      data: {
        'imagebase64': faceImgBase64,
        'person_id': personId,
      },
    ).execute(
      isShowLoading: true,
    );
  }

  /// 删除
  static Future<void> delete() async {
    final personId = UserManager.getUserId();
    if (personId == null) {
      AppToast.showError('无人员ID');
      return;
    }
    await HttpUtil().generatePostRequest<String>(
      Interface.faceDelUrl,
      data: {
        'person_id': personId,
      },
    ).execute();
  }
}
